package nayasis.common.model;

import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Set;

import com.google.gson.Gson;

import nayasis.common.util.StringUtil;


/**
 * Single Data
 * 
 * @author nayasis
 *
 */
public class NData extends LinkedHashMap<Object, Object> {

	private static final long serialVersionUID = 3398423628018291863L;

	public NData() {
	    super();
	}
	
	public NData( String json ) {
	    setFromJson( json );
	}

	public void setFromJson( String json ) {
	    super.putAll( new Gson().fromJson( json, NData.class ) );
	}

	public String toJson() {
	    return new Gson().toJson( this );
	}
	
	public String getString( Object key ) {
		
		Object val = get( key );
		
		if( val == null ) {
			return null;
		} else {
			return val.toString();
		}
	
	}
	
	public int getInteger( Object key ) {
		return Integer.parseInt( StringUtil.nvl(getString(key)) );
	}

	public long getLong( Object key ) {
		return Long.parseLong( StringUtil.nvl(getString(key)) );
	}
	
	public float getFloat( Object key ) {
		return Float.parseFloat( StringUtil.nvl(getString(key)) );
	}
	
	public double getDouble( Object key ) {
		return Double.parseDouble( StringUtil.nvl(getString(key)) );
	}

	public Object put( Object key ) {
		return super.put( key, null );
	}
	
	public Object get( int index ) {
		
		int maxIndex = super.size() - 1;
		
		if( maxIndex < index ) throw new ArrayIndexOutOfBoundsException( String.format("maxIndex : %d, triedIndex : %d", maxIndex, index) );
		
		Set<Object> keySet = super.keySet();
		
        Iterator<Object> iterator = keySet.iterator();
        
        for( int i = 0, iCnt = index - 1; i < iCnt; i++ ) {
            iterator.next();
        }

        Object key = iterator.next();
        
        return super.get( key );
		
	}

}
